#include "socketsync_p.h"
#include <QUdpSocket>
#include <QHostAddress>
#include <QEventLoop>
#include <QTimer>
#include <QtDebug>
#include <QThread>


#define MAX_TIMEOUT_CLICK 10000

SocketSyncPrivate::SocketSyncPrivate(QObject *parent)
    :QObject(parent)
    ,m_udpsocket(NULL)
{
    m_udpsocket = new QUdpSocket;
}

SocketSyncPrivate::~SocketSyncPrivate()
{
    if (m_udpsocket)
    {
        m_udpsocket->close();
        delete m_udpsocket;
        m_udpsocket = NULL;
    }
}

void SocketSyncPrivate::setUdpPort(quint16 port)
{
    bool r = m_udpsocket->bind(port);
    if (!r)
    {
        qWarning() << "port is occupation!";
    }
}

int SocketSyncPrivate::sendUdpMessage(QString msg, QString ip, quint16 port, QString &result)
{

    qint64 size = m_udpsocket->writeDatagram(msg.toLatin1(), QHostAddress(ip),port);

    if (size < 0)
    {
        qWarning() << "send data failed!";
        return -1;  //发送失败
    }

    int count = 0;

RECEIVE:
    bool hasdata = false;
    if((hasdata = m_udpsocket->waitForReadyRead(MAX_TIMEOUT_CLICK)))
    {
        if ((m_udpsocket->hasPendingDatagrams()))
        {
            //读取字段
            QByteArray datagram; //拥于存放接收的数据报
            datagram.resize(m_udpsocket->pendingDatagramSize());
            m_udpsocket->readDatagram(datagram.data(),datagram.size());
            result = QString::fromLocal8Bit(datagram.data());
        }
    }

    if(!result.contains("code"))
    {
        count += 1;
        if (count < 10)
            goto RECEIVE;
    }

    if (!hasdata)
    {
        qWarning() << "recv data timeout!";
        return -2;  //接收超时
    }
    return 0;
}
